package com.qianxun.framework.common.constant;

import com.qianxun.init.listener.SystemPropertiesListener;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 系统常量
 * @author: huwei
 * @date:   2019/10/18 15:22
 * @version:  1.0.0
*/
public class SystemConstant {
    /**
     * 系统根包
     */
    public static final String ROOT_PACKAGE = "com.qianxun";

    /**
     * 常量容器
     */
    private static final Map<String ,String> CONSTANT = new ConcurrentHashMap<>(16);

    /**
     * 被当前类信任的对象 ,只有被当前对象信任才能调用put方法 ，该限定，是为了防止在系统运行中常量被动态修改
     */
    private static final Map<String ,Class<?>> BY_TRUST_CLASS = new ConcurrentHashMap<>(1);
    static{
        BY_TRUST_CLASS.put(SystemPropertiesListener.class.getName() , SystemPropertiesListener.class);
    }

    public static String get(String key){
        return CONSTANT.get(key);
    }

    public static String get(String key ,String def){
        String res = CONSTANT.get(key);
        return res == null ? def : res;
    }

    public static void put(String key ,String val){
        checkTrust();
        CONSTANT.put(key ,val);
    }

    public static void putAll(Map<String ,String> maps){
        checkTrust();
        CONSTANT.putAll(maps);
    }

    private static void checkTrust(){
        if(!isTrustClass()){
            throw new RuntimeException("初始化常量只能在系统启动时修改，或被信任的类对象修改.");
        }
    }

    private static boolean isTrustClass(){
        StackTraceElement[] stack = (new Throwable()).getStackTrace();
        for (StackTraceElement stackTraceElement : stack) {
            if(BY_TRUST_CLASS.get(stackTraceElement.getClassName()) != null){
                return true;
            }
        }
        return false;
    }

    public static void println(){
        System.err.println(CONSTANT);
    }
}
